package deepr.handler;

import deepr.anno.SchemaType;
import deepr.core.DisposeContext;
import deepr.exception.LifeException;
import deepr.src.pg.PgDisposeContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

@Slf4j
public class DistanceHandler extends PropertyHandler {


  @Override
  public StringBuilder select(DisposeContext ctx, String object, String property, Object args) {
    Object p = ctx.getRequestParams();
    Assert.isTrue(p instanceof HashMap, object + ", distance requestParams must be json");
    Assert.isTrue(args.getClass().isArray(), object + ", distance handlerArgs must be array");
    log.debug("requestParams: {}, property: {}, args: {}", ctx.getRequestParams(), property, args);
    HashMap<String, Object> requestParams = (HashMap<String, Object>) ctx.getRequestParams();
    String[] a = (String[]) args;
    String latPro = a[0];
    String lonPro = a[1];
    Object lat = requestParams.get(latPro);
    Object lon = requestParams.get(lonPro);
    StringBuilder sb = new StringBuilder();
    if (ctx.getSchemaType() == SchemaType.PG)
      sb.append("earth_distance(ll_to_earth(").
          append(latPro).append(",").append(lonPro).
          append("),ll_to_earth(").append(lat).append(",").
          append(lon).append(")) as ").append(property);
    else
      sb.append("distance(point({latitude:").append(object).append(".latitude,longitude: ").
          append(object).append(".longitude}), point({latitude:").append(lat).append(",longitude:").append(lon).append("}))");
    return sb;
  }

//    @Override
//    public Object filter(HandlerContext ctx, String property, Object args) throws LifeException {
////        if (ctx.getProperties(ctx).indexOf(property) < 0) {
////            throw new LifeException("Filter By Distance Lack Select property", LifeCycle.FILTER_PARSE, property);
////        }
//        return null;
//    }
//
//    @Override
//    public Object replyBefore(HandlerContext ctx, String object, Object rows) throws LifeException {
//        return null;
//    }


}
